/**
 * @param {number[]} ratings
 * @return {number}
 */
var candy = function (ratings) {
    let len = ratings.length,
        candyArr = new Array(len).fill(1)

    // 从左往右
    for (let i = 1; i < len; i++) {
        if (ratings[i] > ratings[i - 1]) {
            candyArr[i] = candyArr[i - 1] + 1
        }
    }
    // 从右往左
    for (let i = len - 1; i > 0; i--) {
        if (ratings[i] < ratings[i - 1]) {
            candyArr[i - 1] = Math.max(candyArr[i] + 1, candyArr[i - 1])
        }
    }
    return candyArr.reduce((a, b) => a + b)
};


/**
 * @param {number[]} ratings
 * @return {number}
 */
var candy = function (ratings) {
    let minCandyArr = new Array(ratings.length).fill(1),
        left = 0,
        right = 0;
    while (right + 1 < ratings.length) {
        // 上升序列
        if (ratings[right + 1] > ratings[right]) {
            while (right + 1 < ratings.length && ratings[right + 1] > ratings[right]) {
                minCandyArr[right + 1] = minCandyArr[right] + 1
                right++
            }
            left = right
        }

        // 下降序列
        if (ratings[right + 1] <= ratings[right]) {
            while (right + 1 < ratings.length && ratings[right + 1] <= ratings[right]) {
                right++
            }
            for (let i = right - 1; i > left; i--) {
                if (ratings[i] > ratings[i+1]) {
                    minCandyArr[i] = minCandyArr[i+1] + 1
                }
            }
            if(ratings[left] > ratings[left+1]){
                minCandyArr[left] = Math.max(minCandyArr[left], minCandyArr[left+1] + 1)
            }
            left = right
        }
    }
    return minCandyArr.reduce((a,b)=>a+b)
};